#pragma once

#include <iostream>
#include "Connection.hpp"
#include "Protocol.hpp"
#include "Calculate.hpp"

class pakageParse
{
public:
    static void parse(connection *conn)
    {
        std::cout << conn->getInbuffer() << std::endl;
        // conn->appendOutbuffer(conn->getInbuffer());
        while (true)
        {
            // 检验收到的消息是否完整
            // std::cout << "inbuffer: " << inbuffer << std::endl;
            std::string package = DeCode(conn->getInbuffer());
            if (package.empty())
                break;

            std::cout << "package: " << package << std::endl;

            std::cout << "----------------begin-----------------" << std::endl;
            // 收到了完整的消息，将信息反序列化
            Request request;
            request.Deserialize(package);

            // printf("x = %d, y = %d, op = %c\n", request.getX(), request.getY(), request.getOption());

            // 执行任务
            Calculate _cal;
            Response response = _cal.Execute(request);
            // printf("res = %d, code = %d\n", response.getResult(),  response.getCode());

            // 序列化任务结果
            std::string server_result;
            response.Serialize(&server_result);

            // std::cout << "server_result: " << server_result << std::endl;

            // 对任务结果添加报头
            Encode(server_result);

            // std::cout << "server_result: " << server_result << std::endl;
            conn->appendOutbuffer(server_result);   //将处理得到的报文全部添加到连接的outbuffer中
        }
        if (conn->_sender != nullptr)
        {
            conn->_sender(conn);    //直接发送
        }
    } 
};